﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BWmsOutOrderSummary
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/21 15:56:32
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
using KingerRobot.MexicoSailunWMS.Spi;

namespace KingerRobot.MexicoSailunWMS.SpiService;

public class BWmsOutOrderSummary : IWmsOutOrderSummary
{
    private readonly static IBakWmsOutOrderSummary _BakWmsOutOrderSummary = new BBakWmsOutOrderSummary();
    private readonly static IRcsEquipCuring _RcsEquipCuring = new BRcsEquipCuring();
    private readonly static IWcsEquipLoc _WcsEquipLoc = new BWcsEquipLoc();
    public int UpdateSummaryTargetCount(long? id, int count = 0)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id)
            .Update( new POWmsOutOrderSummary
            {
                TargetCount = count,
            });
        return result;
    }
    public int UpdateSummarySafe(long? id, int safe)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id)
            .Update( new POWmsOutOrderSummary
            {
                Safe = safe,
            });
        return result;
    }

    public int ReRequestSummary(long summaryId)
    {
        var summary = GetOutOrderSummaryById(summaryId);
        if (summary is null)
        {
            return 0;
        }
        var targetLoc = summary.TargetLoc.GetValueOrDefault();
        var realCount = summary.RealCount.GetValueOrDefault();
        var equip = _WcsEquipLoc.GetEquipIdByLocId(targetLoc);
        var curing = _RcsEquipCuring.GetCuringById(equip);
        var result = 0;
        if (curing?.IsCuringCall == 0)
        {
            var db = Db.Default;
            result = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId && t.RealCount > 0)
            .Update( new POWmsOutOrderSummary
            {
                // StartLoc = null,
                RealCount = 0,
                RemarkMemo = "WMS 删除重下"
            });
        }

        return result;
    }

    public List<POWmsOutOrderSummary> GetOutOrderSummaryByMasterId(long masterId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).ToList();
        return result;
    }

    public List<POWmsOutOrderSummary> GetOutOrderSummaryByCrnId(long CrnId, ref List<POWcsTask> Task)
    {
        var db = Db.Default;

        var data = db.WcsTasks.Join(db.WmsOutOrderSummarys, f => f.SummaryId, s => s.Id, (f, s) => new
        {
            f,
            s
        })
        .Join(db.RcsEquipCrnToForks, f => f.f.StartEquip, s => s.FolkEquipId, (f, s) => new
        {
            f.f,
            f.s,
            flok = s,
        })
        .Where(t => t.f.TaskStatus == (int)EnumTaskStatus.Executable && t.flok.CrnEquipId == CrnId);
        Task = data.Select(t => t.f).ToList();
        var result = data.Select(t => t.s).ToList();

        return result;
    }

    public bool IsOutOrderSummaryByMasterId(long masterId) => GetOutOrderSummaryByMasterId(masterId).Count() > 0;
    public int BakOutOderSummary(POWmsOutOrderSummary wmsOutOrderSummary)
    {
        if (_BakWmsOutOrderSummary.GetBakWmsOutOrderSummaryById(wmsOutOrderSummary.Id.GetValueOrDefault()) != null)
        {
            return 0;
        }
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.BakWmsOutOrderSummarys.CopyFrom(wmsOutOrderSummary);
        }
        catch (Exception ex)
        {

        };
        return result;
    }
    public int DeleteOutOderSummary(long? id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id).Delete();
        return result;
    }
    public int BakAndDeleteOutOrderSummary(long id)
    {
        var summary = GetOutOrderSummaryById(id);
        if (summary == null)
        {
            return 0;
        }
        var result = UpdateSummaryTargetCount(id, 1);

        result += BakOutOderSummary(summary);

        result += DeleteOutOderSummary(id);

        return result;
    }
    public POWmsOutOrderSummary GetOutOrderSummaryById(long id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id).FirstOrDefault();
        return result;
    }
    public int UpdateOutOrderSummaryFinish(long masterId, int finishMode)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).Update( new POWmsOutOrderSummary
        {
            FinishMode = finishMode,
            FinishTime = DateTime.Now,
        });
        return result;
    }
    [Obsolete("暂未启用", true)]
    public List<POWmsOutOrderSummary> GetOutOrderSummaryList(int type, int status)
    {
        var db = Db.Default;
        var reault = db.WmsOutOrderSummarys
            .Join(db.WmsOutOrderMasters,
            f => f.MasterId,
            s => s.Id, (f, s) => new { Master = s, Summary = f })
            .Where(t => t.Summary.FinishMode == (int)EnumCodeFinishMode.NotFinished &&
            t.Master.OrderStatus == status &&
            t.Master.OrderType == type)
            .OrderBy(t => t.Master.OrderPriority)
            .ThenBy(t => t.Master.CreateTime) // 优先级排序、时间排序
            .Select(t => t.Summary).ToList();
        return reault;
    }
    public int AddOutOrderSummaryListByLoc(List<POWmsOutOrderSummary> WmsOutOrderSummaries)
    {
        if (WmsOutOrderSummaries is null || WmsOutOrderSummaries.Count == 0)
        {
            return 0;
        }
        var db = Db.Default;
        WmsOutOrderSummaries.ForEach(item =>
        {
            item.Id = XID.Nextval;
            db.WmsOutOrderSummarys.Insert(item);
        });

        return 1;
    }
    public List<POWmsOutOrderSummary> GetOrderSummaryList()
    {
        var db = Db.Default;
        var reault = db.WmsOutOrderSummarys.ToList();
        return reault;
    }




    public List<POWmsOutOrderSummary> GetOutOrderSummaryNoTaskList(int type)
    {
        var db = Db.Default;

        var reault = db.WmsOutOrderSummarys
            .Join(db.WmsOutOrderMasters, // 这里关联用到 OrderPriority （优先级）
            f => f.MasterId,
            s => s.Id, (f, s) => new { Master = s, Summary = f })
            .Where(t => t.Summary.FinishMode == (int)EnumCodeFinishMode.NotFinished &&
            t.Summary.PlanCount > t.Summary.RealCount && t.Master.OrderType == type)
            .OrderBy(t => t.Master.OrderPriority)
            .ThenBy(t => t.Master.CreateTime) // 优先级排序、时间排序
            .Select(t => t.Summary).ToList();
        return reault;
    }


    public POWmsOutOrderSummary GetOutOrderSummaryByLocId(long locId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.TargetLoc == locId).FirstOrDefault();
        return result;
    }

    public OutOrderSummaryKanBan GetOutOrderSummarySchedule(POWmsOutOrderSummary summary)
    {
        var db = Db.Default;
        OutOrderSummaryKanBan outOrderSummaryKanBan = new();
        var summaryId = summary.Id ?? 0;
        outOrderSummaryKanBan.OutOrderSummaryId = summaryId;
        //var summary = GetOutOrderSummaryById(summaryId);
        //查询出库轮胎规格信息
        var material = db.ProdMaterials.Where(T => T.Id == summary.MaterialId).FirstOrDefault();
        if (material != null)
        {
            outOrderSummaryKanBan.Spec = material.Spec;
        }
        //查询目的地信息
        var tarLoc = db.RcsLocations.Where(T => T.Id == summary.TargetLoc).FirstOrDefault();
        if (tarLoc != null)
        {
            outOrderSummaryKanBan.TargetLoc = tarLoc.LocName;
            //从名称中分离出左右模信息
            try
            {
                string lOrR = tarLoc.LocName.Split('机')[1].Substring(0, 1);
                outOrderSummaryKanBan.LeftOrRight = Convert.ToInt32(lOrR);
            }
            catch (Exception ex)
            {
                //屏蔽可能的报错
            }
        }

        //查询任务信息
        var task = db.WcsTasks.Where(T => T.SummaryId == summaryId).FirstOrDefault();
        if (task != null)
        {
            outOrderSummaryKanBan.IsCreateTask = 1;
            //根据任务SKU查询条码信息
            var sku = db.ProdSkuProducts.Join(db.ProdProducts, a => a.ProductId, b => b.Id, (a, b) => new { sku = a, product = b }).Where(T => T.sku.SkuId == task.SkuId).FirstOrDefault();
            if (sku != null)
            {
                outOrderSummaryKanBan.Barcode = sku.product.ProductCode;
            }
            outOrderSummaryKanBan.TaskId = task.Id.GetValueOrDefault();
            //任务生成时间
            outOrderSummaryKanBan.OutRealTime = task.CreateTime.GetValueOrDefault();
            outOrderSummaryKanBan.TaskSn = task.TaskNo.GetValueOrDefault();
            //根据任务信息查条码
            var prodSku = db.ProdSkuProducts.Where(T => T.SkuId == task.SkuId).FirstOrDefault();
            if (prodSku != null)
            {
                //查条码
                var product = db.ProdProducts.Where(T => T.Id == prodSku.ProductId).FirstOrDefault();
                if (product != null)
                {
                    outOrderSummaryKanBan.Barcode = product.ProductCode;
                }
            }
            //查询出库位置
            var staLoc = db.RcsLocations.Where(T => T.Id == task.StartLoc).FirstOrDefault();
            if (staLoc != null)
            {
                outOrderSummaryKanBan.StartLoc = staLoc.LocName;
            }

        }
        else
        {
            outOrderSummaryKanBan.IsCreateTask = 0;
        }
        return outOrderSummaryKanBan;
    }
}
